import logging
import os.path
import sys
import time

from PyQt5.QtCore import pyqtSlot, QTimer, Qt
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QMainWindow, QWidget, QLabel, QPushButton, QVBoxLayout, QHBoxLayout, QMenu, QAction, \
    QMessageBox, QStackedLayout

from audio_settings import AudioSettingsWidget
from base_settings import BaseSettingsWidget
from config import config_file_path, version
from home_widget import HomeWidget
from prepare_for_examen import PrepareForExamen
from print_settings import PrintSettingsWidget
from scan_settings import ScanSettingsWidget
from system import run_command


class ArmGiaWindow(QMainWindow):

    @pyqtSlot()
    def update_time(self):
        self.time_value = time.strftime('%H:%M:%S', time.localtime())
        self.system_time_label.setText(f'Системное время: {self.time_value}')
        time.sleep(0.1)

    def save_base_settings(self):
        self.region_label.setText(f'Регион: {self.base_settings_widget.region_combobox.currentText().strip()}')
        self.code_msu_label.setText(f'Код МСУ: {self.base_settings_widget.msu_code_combobox.currentText().strip()}')
        self.code_ppe_label.setText(f'Код ППЭ: {self.base_settings_widget.ppe_code_combobox.currentText().strip()}')
        self.comp_number_label.setText(f'№ компьютера: '
                                       f'{self.base_settings_widget.comp_number_combobox.currentText().strip()}')
        if not os.path.isfile(config_file_path):
            run_command(f'touch {config_file_path}')
            logging.info('Файл конфига не существовал и был создан')
        run_command(f'py-ini-config set {config_file_path} BaseSettings '
                    f'region {self.base_settings_widget.region_combobox.currentText().strip()}')
        run_command(f'py-ini-config set {config_file_path} BaseSettings '
                    f'msu_code {self.base_settings_widget.msu_code_combobox.currentText().strip()}')
        run_command(f'py-ini-config set {config_file_path} BaseSettings '
                    f'ppe_code {self.base_settings_widget.ppe_code_combobox.currentText().strip()}')
        run_command(f'py-ini-config set {config_file_path} BaseSettings '
                    f'comp_number {self.base_settings_widget.comp_number_combobox.currentText().strip()}')
        self.show_home_widget()

    def load_base_setting_from_config_file(self):
        region = run_command(f'py-ini-config get {config_file_path} BaseSettings region').strip()
        msu_code = run_command(f'py-ini-config get {config_file_path} BaseSettings msu_code').strip()
        ppe_code = run_command(f'py-ini-config get {config_file_path} BaseSettings ppe_code').strip()
        comp_number = run_command(f'py-ini-config get {config_file_path} BaseSettings comp_number').strip()
        for config_element in region, msu_code, ppe_code, comp_number:
            if not config_element:
                logging.info(f'Не удалось считать информацию о станции АРМ ГИА-9 из файла конфига')
                return
        self.region_label.setText(f'Регион: {region}')
        self.code_msu_label.setText(f'Код МСУ: {msu_code}')
        self.code_ppe_label.setText(f'Код ППЭ: {ppe_code}')
        self.comp_number_label.setText(f'№ компьютера: {comp_number}')
        self.base_settings_widget.region_combobox.setCurrentText(region)
        self.base_settings_widget.msu_code_combobox.setCurrentText(msu_code)
        self.base_settings_widget.ppe_code_combobox.setCurrentText(ppe_code)
        self.base_settings_widget.comp_number_combobox.setCurrentText(comp_number)

    def show_base_settings_widget(self):
        self.main_widget_stacked_layout.setCurrentIndex(2)
        self.load_base_setting_from_config_file()

    def show_home_widget(self):
        self.main_widget_stacked_layout.setCurrentIndex(0)

    def open_print_settings(self):
        self.print_settings_dialog = PrintSettingsWidget(self)
        self.print_settings_dialog.exec_()

    def open_scan_settings(self):
        self.scan_settings_dialog = ScanSettingsWidget(self)
        self.scan_settings_dialog.exec_()

    def open_audio_settings(self):
        self.audio_settings_dialog = AudioSettingsWidget(self)
        self.audio_settings_dialog.exec_()

    def show_info_menu(self) -> None:
        """
        Показывает контекстное меню при нажатии на кнопку "Информация"
        """
        import_menu = QMenu()
        about_action = QAction("О программе")
        program_info_action = QAction("Сведения о работе ПО")
        about_action.triggered.connect(self.open_about)
        program_info_action.triggered.connect(self.open_program_info)
        import_menu.addAction(about_action)
        import_menu.addAction(program_info_action)
        import_menu.exec(self.cursor().pos())

    def open_about(self):
        dlg = QMessageBox()
        dlg.setWindowTitle('О программе')
        dlg.setText(f'<h2>АРМ ГИА-9 в ППЭ</h2><br>Версия {version}')
        dlg.setIconPixmap(QPixmap('arm-gia9.svg'))
        dlg.exec_()

    def open_program_info(self):
        run_command('konsole -e htop')

    def show_exam_buttons(self, show=True):
        for button in self.prepare_exam_button, self.process_exam_button, self.end_exam_button:
            if show:
                button.show()
            else:
                button.hide()

    def show_prepare_for_examen_widget(self, file=None):
        self.show_exam_buttons(True)
        self.prepare_exam_button.setStyleSheet('QPushButton {background-color: #406840;}')

        if file:
            self.prepare_for_examen_widget = PrepareForExamen(file, self)
        self.main_widget_stacked_layout.replaceWidget(
            self.main_widget_stacked_layout.widget(1),
            self.prepare_for_examen_widget
        )
        self.main_widget_stacked_layout.setCurrentIndex(1)

    def __init__(self):
        QMainWindow.__init__(self)

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        central_widget_layout = QVBoxLayout()
        central_widget.setLayout(central_widget_layout)

        upper_widget = QWidget()
        upper_widget_layout = QHBoxLayout()
        upper_widget.setLayout(upper_widget_layout)
        self.region_label = QLabel('Регион: -')
        self.code_msu_label = QLabel('Код МСУ: -')
        self.code_ppe_label = QLabel('Код ППЭ: -')
        self.comp_number_label = QLabel('№ Компьютера: -')
        self.system_time_label = QLabel('Системное время: -')
        upper_widget_layout.addWidget(self.region_label)
        upper_widget_layout.addWidget(self.code_msu_label)
        upper_widget_layout.addWidget(self.code_ppe_label)
        upper_widget_layout.addWidget(self.comp_number_label)
        upper_widget_layout.addWidget(self.system_time_label)
        upper_widget_layout.setAlignment(Qt.AlignLeft)
        upper_widget.setObjectName('upper_widget')

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_time)
        self.timer.start()

        central_widget_layout.addWidget(upper_widget)

        self.lower_widget = QWidget()
        self.lower_widget_layout = QHBoxLayout()
        self.lower_widget.setLayout(self.lower_widget_layout)

        self.left_widget = QWidget()
        left_widget_layout = QVBoxLayout()
        self.left_widget.setLayout(left_widget_layout)
        self.left_widget.setObjectName('left_widget')

        home_button = QPushButton('🏠\nГлавная')
        home_button.clicked.connect(self.show_home_widget)
        home_button.setObjectName('home_button')
        left_widget_layout.addWidget(home_button)

        self.prepare_exam_button = QPushButton('🏗\nПодготовка')
        self.prepare_exam_button.setObjectName('prepare_exam_button')
        self.prepare_exam_button.clicked.connect(self.show_prepare_for_examen_widget)
        left_widget_layout.addWidget(self.prepare_exam_button)
        self.process_exam_button = QPushButton('🗝️\nПроведение')
        self.process_exam_button.setObjectName('process_exam_button')
        left_widget_layout.addWidget(self.process_exam_button)
        self.end_exam_button = QPushButton('📄\nЗавершение')
        self.end_exam_button.setObjectName('end_exam_button')
        left_widget_layout.addWidget(self.end_exam_button)
        self.show_exam_buttons(False)

        left_widget_layout.addStretch()
        settings_button = QPushButton('⚙️')
        settings_button.clicked.connect(self.show_base_settings_widget)
        print_button = QPushButton('🖨️')
        print_button.clicked.connect(self.open_print_settings)
        scan_button = QPushButton('👁')
        scan_button.clicked.connect(self.open_scan_settings)
        audio_button = QPushButton('🔊')
        audio_button.clicked.connect(self.open_audio_settings)
        info_button = QPushButton('ℹ️')
        info_button.clicked.connect(self.show_info_menu)
        left_widget_layout.addWidget(settings_button)
        left_widget_layout.addWidget(print_button)
        left_widget_layout.addWidget(scan_button)
        left_widget_layout.addWidget(audio_button)
        left_widget_layout.addWidget(info_button)

        self.left_widget.setFixedWidth(70)
        self.lower_widget_layout.addWidget(self.left_widget)

        self.main_widget = QWidget()
        self.main_widget_stacked_layout = QStackedLayout()
        self.main_widget.setLayout(self.main_widget_stacked_layout)

        self.home_widget = HomeWidget(self)
        # index 0
        self.main_widget_stacked_layout.addWidget(self.home_widget)

        self.prepare_for_examen_widget = QWidget()
        # index 1
        self.main_widget_stacked_layout.addWidget(self.prepare_for_examen_widget)

        self.base_settings_widget = BaseSettingsWidget()
        self.base_settings_widget.save_button.clicked.connect(self.save_base_settings)
        # index 2
        self.main_widget_stacked_layout.addWidget(self.base_settings_widget)

        self.lower_widget_layout.addWidget(self.main_widget)

        central_widget_layout.addWidget(self.lower_widget)

        self.show_base_settings_widget()
        region = run_command(f'py-ini-config get {config_file_path} BaseSettings region').strip()
        msu_code = run_command(f'py-ini-config get {config_file_path} BaseSettings msu_code').strip()
        ppe_code = run_command(f'py-ini-config get {config_file_path} BaseSettings ppe_code').strip()
        comp_number = run_command(f'py-ini-config get {config_file_path} BaseSettings comp_number').strip()
        for config_element in region, msu_code, ppe_code, comp_number:
            if not config_element:
                break
        else:
            self.show_home_widget()
        self.showMaximized()
        self.setWindowTitle(f"АРМ ГИА-9 в ППЭ, версия {version}")
        self.show()
